package jpavlich.cardsorter;

import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.geom.Point2D;

import fr.inria.zvtm.animation.Animation;
import fr.inria.zvtm.animation.interpolation.IdentityInterpolator;
import fr.inria.zvtm.engine.Camera;
import fr.inria.zvtm.engine.VCursor;
import fr.inria.zvtm.engine.View;
import fr.inria.zvtm.engine.ViewPanel;
import fr.inria.zvtm.engine.VirtualSpaceManager;
import fr.inria.zvtm.event.ViewAdapter;
import fr.inria.zvtm.glyphs.Glyph;

class CardSorterEventListener extends ViewAdapter {

	static float ZOOM_SPEED_COEF = 1.0f / 50.0f;
	static double PAN_SPEED_COEF = 50.0;

	private boolean isDragging = false;

	CardSorter app;

	double lastVX;
	double lastVY;
	private Point2D.Double absPos = new Point2D.Double();

	CardSorterEventListener(CardSorter app) {
		this.app = app;
	}

	public void press1(ViewPanel v, int mod, int jpx, int jpy, MouseEvent e) {
		try {
			app.stickGlyph();
		} catch (NullPointerException ex) {
		}
	}

	public void press3(ViewPanel v, int mod, int jpx, int jpy, MouseEvent e){
    	app.animate();
    	
    }


	public void release1(ViewPanel v, int mod, int jpx, int jpy, MouseEvent e) {
		isDragging = false;
		v.setDrawSegment(false);
		app.unstickGlyphs();
	}

	public void mouseDragged(ViewPanel v, int mod, int buttonNumber, int jpx,
			int jpy, MouseEvent e) {
		if (buttonNumber == 2) {
			if (!isDragging) {
				updateAbsPos(v, app.getCamera());
			}
			isDragging = true;
			updateAbsPos(v, app.getCamera());
			Camera c = app.getCamera();
			c.vx -= absPos.getX() - lastVX;
			c.vy -= absPos.getY() - lastVY;
			System.out.println(v.getVCursor() + "\n " + lastVX + " " + lastVY);
		}
	}

	private void updateAbsPos(ViewPanel v, Camera c) {
		lastVX = absPos.getX();
		lastVY = absPos.getY();
		absPos = v.getVCursor().getVSCoordinates(c);
		absPos.x -= c.vx;
		absPos.y -= c.vy;
	}

	public void mouseWheelMoved(ViewPanel v, short wheelDirection, int jpx,
			int jpy, MouseWheelEvent e) {
		Camera c = app.getCamera();
		double a = (c.focal + Math.abs(c.altitude)) / c.focal;
		if (wheelDirection == WHEEL_DOWN) {
			c.altitudeOffset(-a * 5);
			VirtualSpaceManager.INSTANCE.repaint();
		} else {
			// wheelDirection == WHEEL_UP
			c.altitudeOffset(a * 5);
			VirtualSpaceManager.INSTANCE.repaint();
		}
	}

	public void enterGlyph(Glyph g) {
		g.highlight(true, null);
		System.out.println(g);
	}

	public void exitGlyph(Glyph g) {
		g.highlight(false, null);
	}

	public void Kpress(ViewPanel v, char c, int code, int mod, KeyEvent e) {
	}

	public void viewClosing(View v) {
		System.exit(0);
	}

}